﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace Web.live
{
    /// <summary>
    /// update 的摘要说明
    /// </summary>
    public class update : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            string sn = string.IsNullOrEmpty(context.Request.Form["sn"]) ? context.Request.QueryString["sn"] : context.Request.Form["sn"];
            string zbj = string.IsNullOrEmpty(context.Request.Form["zbj"]) ? context.Request.QueryString["zbj"] : context.Request.Form["zbj"];
            string dn = string.IsNullOrEmpty(context.Request.Form["dn"]) ? context.Request.QueryString["dn"] : context.Request.Form["dn"];
            string type = string.IsNullOrEmpty(context.Request.Form["type"]) ? context.Request.QueryString["type"] : context.Request.Form["type"];
            string v = string.IsNullOrEmpty(context.Request.Form["v"]) ? context.Request.QueryString["v"] : context.Request.Form["v"];
            string returnstr = "请联系QQ:9021616 购买注册";

            //免费使用
            string mf = ReadFile(System.Web.HttpContext.Current.Server.MapPath("/live/ks/") + "mf.html");
            if (mf == "QQ9021616")
            {
                string mfsj = DateTime.Now.AddDays(5).ToString("yyyy-MM-dd");
                returnstr = res(mfsj + type + sn);
            }
            else
            {
                string IP = LJSheng.Common.LCommon.GetIPAddress(context);
                StreamWriter sr = null;
                //启动日志
                try
                {
                    //启动日志
                    string qdpath = System.Web.HttpContext.Current.Server.MapPath(type == "TB" ? "/live/tb/" : "/live/qd/") + sn + ".html";
                    if (zbj == "djs" && type == "qd")
                    {
                        qdpath = System.Web.HttpContext.Current.Server.MapPath("/TB/djs/") + sn + ".html";
                    }
                    if (!File.Exists(qdpath))
                    {
                        sr = File.CreateText(qdpath);
                        sr.WriteLine(DateTime.Now.ToString());
                    }
                    else
                    {
                        File.AppendAllText(qdpath, v + "-" + DateTime.Now.ToString() + " - " + "zbj=" + zbj + ",DN=" + dn + ",type=" + type + ",IP=" + IP + "\r\n");
                    }
                    //限制IPSN登录
                    bool isdb = false;
                    string ckip = ReadFile(System.Web.HttpContext.Current.Server.MapPath("/live/ip/") + "ip.html");
                    if (ckip.Contains(sn) || (!string.IsNullOrEmpty(IP) && ckip.Contains(IP)))
                    {
                        //isdb = true;
                        returnstr = "";
                    }
                    else
                    {
                        //读取注册码
                        returnstr = ReadFile(System.Web.HttpContext.Current.Server.MapPath("/live/") + sn + ".html");
                        //是否限制电脑
                        if (string.IsNullOrEmpty(returnstr))
                        {
                            //isdb = true;
                        }
                    }
                    string rq1 = "2020-02-02";
                    string rq2 = "2020-02-02";
                    if (!string.IsNullOrEmpty(returnstr) && returnstr != "http://520299.com")
                    {
                        JToken paramJson = JToken.Parse(returnstr);
                        if (type == "node" || type == "qd" || type == "js" || type == "dn")
                        {
                            returnstr = POSTWebRequestDotnetReference("http://zb.fpzs110.com/live/zb.ashx?v=520299&type=qd&sn=" + sn + "&zbj=" + zbj);
                            #region 不支持的代码
                            //string rq = ReadFile(System.Web.HttpContext.Current.Server.MapPath("/live/ks/") + "rq.html");
                            //if (!string.IsNullOrEmpty(rq))
                            //{
                            //    rq1 = rq.Split('#')[0];
                            //    rq2 = rq.Split('#')[1];
                            //}

                            //JObject jo = JObject.Parse(returnstr);
                            //jo.Remove("linjiansheng");
                            //jo.Remove("LJSHENG");
                            //jo["data"]["pass"] = "C3321DEB628BE5343C72EB0BA71DDA16";
                            //jo.Add("miao", 0);
                            //jo.Add("update", JToken.FromObject(new
                            //{
                            //    useridlogin = "ok",
                            //    node = rq1,
                            //    gift = rq2
                            //}));
                            //jo.Add("txt", JToken.FromObject(new
                            //{
                            //    fwq = "",
                            //    bat = "",
                            //    login = "",
                            //    ck = "",
                            //    share = "",
                            //    config = "",
                            //    db = ""
                            //}));
                            //returnstr = JsonConvert.SerializeObject(jo, Formatting.Indented);
                            #endregion
                        }
                        else
                        {
                            if (type == "sq")
                            {
                                if (DateTime.Parse(paramJson["data"]["time"].ToString()) < DateTime.Now)
                                { returnstr = "注册成功,技术支持QQ9021616"; }
                            }
                            else
                            {
                                //去对应的模板授权数据
                                if (paramJson != null && paramJson["linjiansheng"][type.ToLower()] != null)
                                {
                                    returnstr = paramJson["linjiansheng"][type.ToLower()].ToString();
                                }
                            }
                        }
                    }
                    else if (string.IsNullOrEmpty(returnstr))
                    {
                        //网络没有认证信息
                        if ((zbj.ToLower() != "djs" && type != "qd") || type.ToLower() != "TB")
                        {
                            StreamWriter db = null;
                            try
                            {
                                string dbpath = System.Web.HttpContext.Current.Server.MapPath("/TB/") + sn + ".html";
                                if (!File.Exists(dbpath))
                                {
                                    db = File.CreateText(dbpath);
                                    db.WriteLine(DateTime.Now.ToString());
                                }
                                else
                                {
                                    File.AppendAllText(dbpath, v + "-" + DateTime.Now.ToString() + " - " + "zbj=" + zbj + ",DN=" + dn + ",type=" + type + ",IP=" + IP + "\r\n");
                                }
                            }
                            catch
                            {
                                //returnstr = "http://520299.com";
                            }
                            finally
                            {
                                if (db != null)
                                {
                                    db.Close();
                                    db.Dispose();
                                }
                            }
                        }
                        if (type.ToLower() == "qd" || type.ToLower() == "node" || type.ToLower() == "js" || type == "dn")
                        {
                            returnstr = POSTWebRequestDotnetReference("http://zb.fpzs110.com/live/zb.ashx?v=520299&type=qd&sn=" + sn + "&zbj=" + zbj);
                            #region 无法执行代码
                            //JObject jo = JObject.Parse("{\"miao\":" + LJSheng.Common.RandStr.CreateValidateNumber(1) + "}");
                            //jo.Add("data", JToken.FromObject(new
                            //{
                            //    time = "2020-11-11"
                            //}));
                            //jo.Add("update", JToken.FromObject(new
                            //{
                            //    useridlogin = "ok",
                            //    node = "2021-01-05",
                            //    gift = rq2
                            //}));
                            //jo.Add("txt", JToken.FromObject(new
                            //{
                            //    fwq = "",
                            //    bat = "",
                            //    //login = "db2c5c0ae37fee4a8a35033ee=1608619639;userId=1424589533;kuaishou.live.web_st=ChRrdWFpc2hvdS5saXZlLndlYi5zdBKgAY1MKBX-RNw43zWaa53TNPm1Jb8fXeND4129u3G6ghzGKG6_dKZOq2NjvgZLyp2y1n8Mil-ky4P6nLAnoRo3a3E0l7Dt03XsGy7AMWrWUelhlFzEWFsfnz9WncNLiySgChMFnhQMj1t7YpzbzygmkMKzuxeOZE-H0eJQat1N2oyqLHfnqHAnyAFwzaPzpBcrRSTDYtjY_gc2f404z015sIkaEo_d-PiuxE4duU2DjxXdbB5BSiIgjHAwUv69UIE0BM0681_Tupqc6a31yK_SahLRBJF-qsYoBTAB;kuaishou.live.web_ph=a51f952d2550d41e386d1e5eed2eaf40630a;userId=1424589533",
                            //    login = "",
                            //    ck = "",
                            //    share = "",
                            //    config = "",
                            //    db = "",
                            //    zhibo = ""
                            //    //db = "[LJSHENG]\r\nFWQ = \u670d\u52a1\u56681\r\nKSZBJ = jjworld126\r\n",
                            //    //zhibo = "[LJSHENG]\r\nFWQ = \u670d\u52a1\u56681\r\nKSZBJ = jjworld126\r\n"
                            //}));
                            //if (isdb == true)
                            //{
                            //    jo.Add("dnml", JToken.FromObject(new
                            //    {
                            //        cq = "shutdown -r -f -t 0",
                            //        gj = "shutdown -s -f -t 0"
                            //    }));
                            //    jo.Add("ks", JToken.FromObject(new
                            //    {
                            //        kspath = @"\KwaiLive\basic\scenes\basic-scenes.json",
                            //        json = ""
                            //    }));
                            //    jo.Add("node", JToken.FromObject(new
                            //    {
                            //        exe = "9021616.exe",
                            //        rar = "ks.rar"
                            //    }));
                            //}
                            //returnstr = JsonConvert.SerializeObject(jo, Formatting.Indented);
                            #endregion
                        }
                        else
                        {
                            if (isdb)
                                returnstr = "\u005b\u534a\u534a\u8f6f\u4ef6\u005d\u5df2\u7533\u8bf7\u8f6f\u4ef6\u8457\u4f5c\u6743\u002c\u4f60\u7684\u0069\u0070\u5730\u5740\u6211\u4eec\u5df2\u62a5\u7ed9\u6c5f\u82cf\u516c\u5b89\u5c40\u002c\u4f60\u4f7f\u7528\u7684\u662f\u76d7\u7248\u002e\u73b0\u5df2\u544a\u77e5\u4f60\u002c\u5982\u679c\u4f60\u7ee7\u7eed\u4f7f\u7528\u5c31\u662f\u89e6\u72af\u0028\u6c11\u6cd5\u5178\u7b2c\u0031\u0032\u0033\u6761\u0029\u518d\u4f7f\u7528\u5c31\u4fb5\u72af\u8f6f\u4ef6\u8457\u4f5c\u6743\u002e\u5982\u679c\u4f60\u662f\u4e0d\u77e5\u60c5\u60c5\u51b5\u88ab\u9a97\u94b1\u8bf7\u62a5\u8b66\u5904\u7406\u002e\u540c\u65f6\u4fdd\u7559\u4f60\u7684\u4ed8\u6b3e\u8bc1\u636e\u002e\u6211\u4eec\u5df2\u62a5\u6848\u002c\u5230\u65f6\u5019\u914d\u5408\u8b66\u65b9\u53d6\u8bc1\u002c\u76ee\u524d\u7834\u89e3\u4eba\u4fe1\u606f\u516c\u5b89\u673a\u5173\u5df2\u638c\u63e1\u002c\u5982\u679c\u4f60\u4e70\u8fc7\u6b63\u7248\u7136\u800c\u5728\u516c\u53f8\u4f7f\u7528\u4e86\u76d7\u7248\u5c06\u4f1a\u5168\u90e8\u53d8\u6210\u76d7\u7248\u8bf7\u91cd\u65b0\u8d2d\u4e70\u002e\u8d2d\u4e70\u6b63\u7248\u552f\u4e00\u6280\u672f\u0028\u534a\u534a\u0029\u0051\u0051\u0039\u0030\u0032\u0031\u0036\u0031\u0036";
                        }
                    }
                }
                catch (Exception err)
                {
                    returnstr = "http://520299.com";
                }
                finally
                {
                    if (sr != null)
                    {
                        sr.Close();
                        sr.Dispose();
                    }
                }
                //同IP记录
                if (!string.IsNullOrEmpty(IP) && IP.Length > 8)
                {
                    try
                    {
                        if (LJSheng.Common.LCommon.checkIP(IP))
                        {
                            using (StreamWriter sw = new StreamWriter(System.Web.HttpContext.Current.Server.MapPath("/live/ip/") + IP + ".html", true, Encoding.UTF8))
                            {
                                sw.Write(v + "-" + DateTime.Now.ToString() + "-" + sn + " - " + zbj + "\r\n");
                                sw.Close();
                                sw.Dispose();
                            }
                        }
                        using (StreamWriter sw = new StreamWriter(System.Web.HttpContext.Current.Server.MapPath("/live/") + "zbj.html", true, Encoding.UTF8))
                        {
                            sw.Write(sn + "-" + IP + "-" + zbj + "\r\n");
                            sw.Close();
                            sw.Dispose();
                        }
                    }
                    catch { }
                }
            }
            if (!string.IsNullOrEmpty(returnstr))
                context.Response.Write(returnstr.Replace("\r", "").Replace("\n", ""));
            context.Response.End();
        }

        public string POSTWebRequestDotnetReference(string url)
        {
            try
            {
                byte[] byteArray = System.Text.Encoding.UTF8.GetBytes("");
                HttpWebRequest objWebRequest = (HttpWebRequest)WebRequest.Create(url); //发送地址
                objWebRequest.Method = "POST";//提交方式
                objWebRequest.ContentType = "application/json;charset=UTF-8";
                objWebRequest.ContentLength = byteArray.Length;
                using (Stream newStream = objWebRequest.GetRequestStream())
                {
                    newStream.Write(byteArray, 0, byteArray.Length); //写入参数
                    newStream.Close();
                }
                HttpWebResponse response = (HttpWebResponse)objWebRequest.GetResponse();//获取响应
                StreamReader sr = new StreamReader(response.GetResponseStream(), System.Text.Encoding.UTF8);
                return sr.ReadToEnd(); // 返回的数据
            }
            catch (Exception err) { return "http://520299.com"; }
        }

        public string res(string es)
        {
            //<RSAKeyValue><Modulus>r8l3eiVWgQLo/kmt1mmMLAT8EUV3vE6TgKxkJV5yq5BvwrOGvpa7EoSSAFHrQsYBoi228TT0riE0mN+P6/gYFuAb1E29GYInbvH+aPouVQdAaNVBmAqmQOM/lAgKGxU6H+PHYtj5YnnmfwJR4jYb0RnmV3u8XSpNKv1KtGt1Ojk=</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>
            LJSheng.Common.RSA rsa = new LJSheng.Common.RSA();
            string pubkey = @"<RSAKeyValue><Modulus>r8l3eiVWgQLo/kmt1mmMLAT8EUV3vE6TgKxkJV5yq5BvwrOGvpa7EoSSAFHrQsYBoi228TT0riE0mN+P6/gYFuAb1E29GYInbvH+aPouVQdAaNVBmAqmQOM/lAgKGxU6H+PHYtj5YnnmfwJR4jYb0RnmV3u8XSpNKv1KtGt1Ojk=</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>";
            return rsa.Encrypt(pubkey, es);
        }

        /// <summary>
        /// 向同一个地址发送请求时会发生：基础连接已经关闭: 服务器关闭了本应保持活动状态的连接的问题
        /// </summary>
        /// <param name="url"></param>
        /// <param name="method"></param>
        /// <returns></returns>
        public static string GetWebRequestDotnetReference(string url, string method)
        {
            string retString;
            try
            {
                HttpWebRequest request = null;
                if (url.Contains("https"))
                {
                    //ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(this.CheckValidationResult);
                    request = (HttpWebRequest)WebRequest.CreateDefault(new Uri(url));
                }
                else
                {
                    request = (HttpWebRequest)WebRequest.Create(url);
                }

                request.Method = method;
                request.KeepAlive = false;//fase
                request.ProtocolVersion = HttpVersion.Version11;//Version11
                request.UserAgent = "stgp";
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                Stream myResponseStream = response.GetResponseStream();
                StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
                //返回内容
                retString = myStreamReader.ReadToEnd();
            }
            catch { return null; }
            return retString;
        }


        /// <summary>
        /// 读取文件
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        private string ReadFile(string path)
        {
            string s = "";
            if (File.Exists(path))
            {
                StreamReader myreader = null;
                try
                {
                    myreader = File.OpenText(path);
                    s = myreader.ReadToEnd();
                }
                catch
                {
                    s = "http://520299.com";
                }
                finally
                {
                    if (myreader != null)
                    {
                        myreader.Close();
                        myreader.Dispose();
                    }
                }
            }
            return s;
        }

        /// <summary>
        /// DES解密字符串
        /// </summary>
        /// <param name="decryptString">待解密的字符串</param>
        /// <param name="decryptKey">解密密钥,要求为8位,和加密密钥相同</param>
        /// <returns>解密成功返回解密后的字符串，失败返源串</returns>
        public string Decrypt(string decryptString, string decryptKey)
        {
            try
            {
                DESCryptoServiceProvider des = new DESCryptoServiceProvider
                {
                    Mode = System.Security.Cryptography.CipherMode.ECB
                };
                byte[] inputByteArray = new byte[decryptString.Length / 2];
                for (int x = 0; x < decryptString.Length / 2; x++)
                {
                    int i = (Convert.ToInt32(decryptString.Substring(x * 2, 2), 16));
                    inputByteArray[x] = (byte)i;
                }
                des.Key = ASCIIEncoding.ASCII.GetBytes(decryptKey);
                des.IV = ASCIIEncoding.ASCII.GetBytes(decryptKey);
                MemoryStream ms = new MemoryStream();
                CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write);
                cs.Write(inputByteArray, 0, inputByteArray.Length);
                cs.FlushFinalBlock();
                StringBuilder ret = new StringBuilder();
                return Encoding.Default.GetString(ms.ToArray());
            }
            catch
            {
                return null;
            }
        }


        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}